import React, { PureComponent } from 'react';
import { connect } from 'dva';
import styles from './MenuManager.less';
import { Card,Form,Table,Tag,Icon,Button,Modal,Input,InputNumber,Divider,TreeSelect,Radio, Select,DatePicker,Switch    } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Types,getTypes } from '../../common/constant/Type';
import { NewForm } from 're-antd';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
var initLoading = false;
const columns = [
  {
    title: '菜单名称',
    dataIndex: 'name',
    key: 'name',
    
  }, {
    title: 'ID',
    dataIndex: 'menuId',
    key: 'menuId',
  },{
    title: '图标',
    dataIndex: 'icon',
    render: val => <Icon type={val} style={{ fontSize: 24}} />,
  },{
    title: '类型',
    dataIndex: 'type',
    render: val => <Tag color={getTypes(val).COLOR}>{getTypes(val).NAME}</Tag>,
  },{
    title: '排序',
    dataIndex: 'orderNum',
  },,{
    title: '菜单URL',
    dataIndex: 'url',
  }, {
    title: '授权标识',
    dataIndex: 'perms',
  },
];
@connect(state => ({
  menu: state.menu,
}))
@Form.create()
export default class MenuManager extends PureComponent {

  state = {
    postVisible: false,
    modalTitle:"修改菜单",
    postValue:{},
  };
  
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'menu/fetch',
    });
    if(!initLoading){
      dispatch({
        type:'menu/judgePermission',
      }).then((permission)=>{
        if(permission.edit||permission.delete){
          columns.push({
              title: '操作',
              filterDropdownVisible: false,
              render: (text, record, index) => (
                <div>
                  <a onClick={() =>  this.initEditValue(record)} hidden={!permission.edit}>修改</a>
                  <Divider type="vertical" hidden={!permission.edit}/>
                  <a onClick={()=> this.doDelete(record.menuId)} hidden={!permission.delete}>删除</a>
                </div>
              ),
              
          });
        }
      });

      initLoading= true;
    }
  }
  //新建时初始化
  initNewValue = (flag)=>{
    this.setState({
      modalTitle:"新建菜单",
      postValue:{
        orderNum:0,
        type:0,
        menuId:0,
        parentName:"一级菜单",
        parentId:"0",
      }
    });
    this.changePostVisible(flag);
  }

  //编辑时初始化
  initEditValue = (record)=> {
    this.setState({
      modalTitle:"修改菜单",
      postValue:{
         menuId:record.menuId,
         name:record.name,
         orderNum:record.orderNum,
         icon:record.icon,
         parentId:record.parentId,
         type:record.type,
         perms:record.perms,
         url:record.url,
      }
    });
    this.changePostVisible(true);
  }

  doPost = (value)=>{
    const { dispatch } = this.props;
    return dispatch({
      type: 'menu/post',
      payload:value,
    }).then((res) =>{
      this.showResult(res);
      this.changePostVisible();
    });
  }

  doDelete = (menuId)=>{
    const { dispatch } = this.props;
    const deleteId ={
      menuId:menuId,
    }
    const isThis = this;//onOk中拿不到this，这里定义一个变量传值
    Modal.confirm({
      title: '删除菜单',
      content: '是否删除该菜单?',
      onOk() {
        dispatch({
          type: 'menu/delete',
          payload:deleteId,
        }).then((res) =>{
            isThis.showResult(res);
            isThis.changePostVisible();
        });
      },
      onCancel() {
      },
    });
  }

  changePostVisible = (flag) => {
    if(!!flag===true && this.newform!=undefined){
      this.newform.reset();    
    }
    this.setState({
      postVisible: !!flag,
    });
  }


  showResult = (response)=>{
    if(response.code===200){
      Modal.success({
        title: '成功',
        content: '成功',
      });
      //更新菜单
      this.props.dispatch({
        type: 'menu/fetch',
      });
    }else{
      Modal.error({
        title: '失败',
        content: '失败',
      });
    }
  }

  setSelectTree = (data) =>{
    var treeData = [{
        value:"0",
        label:"一级菜单",
        children:[]
      }];
      treeData[0].children=JSON.parse(JSON.stringify(data));
      this.setTreeDataWithoutButton(treeData[0].children);
      return treeData;
  }

    setTreeDataWithoutButton = (data) =>{
      if(data==null){
        return;
      }
      data.forEach((item)=>{
        item.value=item.menuId+"";        
        item.label=item.name;
        if(item.type==Types.CATALOG.VALUE){
          this.setTreeDataWithoutButton(item.children);
        }else{
          item.children=[];
        }
      });
      return data;
    }

  render() {
   const { loading,permission,menuTree } = this.props.menu;
   const { postVisible,postValue,modalTitle } = this.state;


    return (
    <PageHeaderLayout>
      <div className={styles.standardTable}>
          <Card bordered={false}>
            <div className={styles.tableList}>

              <div className={styles.tableListOperator} hidden={!permission.save}>
                <Button icon="plus" type="primary"  onClick={() => this.initNewValue(true)} >
                  新建
                </Button>
              </div>
            
              <Table columns={columns}  
                    dataSource={menuTree} 
                    loading={loading} 
                    pagination={false} 
                    bordered
              />
            </div>
          </Card>

          <Modal
            maskClosable={false}               
            title={modalTitle}
            visible={postVisible}
            // onOk={this.doPost}
            onCancel={() => this.changePostVisible()}
            footer={null}
          >
            <NewForm
              wrappedComponentRef={(v) => this.newform = v}
              button={
                [{ text: '确定', type: 'primary', onClick: 'sumbit' },{ text: '取消', onClick: ()=>this.changePostVisible() }]
              }
              onSubmit={(value)=>{
                return this.doPost(value);
                // return this.props.dispatch({
                //   type: 'menu/post',
                //   payload:value,
                // });
              }}
              defaultValue={postValue}
              quickReset={true}
              col={1}
              items={[
                {
                  key: 'menuId',
                  component: <Input hidden={true} disabled={true}/>,
                },
                {
                  key: 'type',
                  label: '菜单类型',
                  component: 
                    <RadioGroup>
                        <Radio value={Types.CATALOG.VALUE}>{Types.CATALOG.NAME}</Radio>
                        <Radio value={Types.MENU.VALUE}>{Types.MENU.NAME}</Radio>
                        <Radio value={Types.BUTTON.VALUE}>{Types.BUTTON.NAME}</Radio>
                    </RadioGroup>,
                },
                {
                  rules: [{ required: true, message: '请输入菜单名称!' }],
                  key: 'name',
                  label: '菜单名称',
                  layout:{labelSpan: 5,componentSpan: 15},
                  component: <Input />,
                },
                {
                  rules: [{ required: true, message: '请选择上级菜单!' }],
                  key: 'parentId',
                  defaultValueFormat: v => `${v}`,//将long转化为string
                  label: '上级菜单',
                  layout:{labelSpan: 5,componentSpan: 15},                  
                  component: <TreeSelect
                    showSearch
                    allowClear
                    treeDefaultExpandAll
                    treeData={this.setSelectTree(menuTree)}
                  >
                  </TreeSelect>,
                },
                {
                  key: 'url',
                  label: '菜单Url',
                  layout:{labelSpan: 5,componentSpan: 15},                  
                  component: <Input disabled={this.state.menuType===Types.BUTTON.VALUE?true:false}/>,
                },
                {
                  key: 'perms',
                  label: '授权标识',
                  layout:{labelSpan: 5,componentSpan: 15},
                  component: <Input />,
                },
                {
                  key: 'icon',
                  label: '图标',
                  layout:{labelSpan: 5,componentSpan: 15},
                  extra:"https://ant.design/components/icon-cn/",
                  component: <Input  />,
                },
                {
                  key: 'orderNum',
                  label: '菜单排序',
                  layout:{labelSpan: 5,componentSpan: 15},
                  component: <InputNumber min={0} />,
                },
              ]}
              onValuesChange={
                (props,changedValue,allValues)=>{
                  if(allValues.type != this.state.menuType){
                    this.setState({
                      menuType:allValues.type
                    });
                  }
                }
              }
            />
          </Modal>
      </div>
      </PageHeaderLayout>
    );
  }
}
